package com.example.swimmingpool.service.login;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.example.swimmingpool.SwimmingPoolThreadLocal;
import com.example.swimmingpool.constants.RedisConstants;
import com.example.swimmingpool.entity.user.User;
import com.example.swimmingpool.enums.HttpEnum;
import com.example.swimmingpool.mapper.user.UserMapper;
import com.example.swimmingpool.util.RedisUtil;
import com.example.swimmingpool.util.TokenUtil;
import com.example.swimmingpool.vo.login.LoginVo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginService {

    @Resource
    private RedisUtil redis;
    @Resource
    private UserMapper userMapper;

    public String login(LoginVo loginVo) {
        var count = new LambdaQueryChainWrapper<>(userMapper)
                .eq(User::getUsername, loginVo.getUsername())
                .eq(User::getPassword, loginVo.getPassword())
                .isNotNull(User::getPassword)
                .last("limit 1")
                .count();
        if (count == 0) {
            return HttpEnum.LOGIN_ACCOUNT_ERROR.getMsg();
        }
        var userId = new LambdaQueryChainWrapper<>(userMapper)
                .select(User::getId)
                .like(User::getUsername, loginVo.getUsername())
                .like(User::getPassword, loginVo.getPassword())
                .last("limit 1")
                .one()
                .getId()
                .toString();
        var token = TokenUtil.generateToken();
        var key = RedisConstants.SWIMMING_USER + token;
        redis.set(key, userId, RedisConstants.SWIMMING_USER_EXPIRE, TimeUnit.DAYS);
        return token;
    }
}
